package com.zou.zkclient;

import com.zou.Ticket12306;

import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.locks.Lock;

public class ZkClientLockTest implements Runnable {

	// 线程数
	private static final int NUM = 20;

	//发令枪，可以控制多个线程同时并发执行, countDown()每次调用 NUM - 1, 为0时, 自动唤醒所有cdl.await() 线程
	private static CountDownLatch cdl = new CountDownLatch(NUM);

	//12306 核心业务对象
	private static Ticket12306 ticket12306 = new Ticket12306();

	//公司列表
	private static String[] components = new String[]{ "飞猪", "携程", "去哪", "智行"};

	private Lock lock = new ZkClientLock();


	public static void main(String[] args) {

		for (int i = 1; i <= NUM; i++) {
			// 按照线程数迭代实例化线程
			new Thread(new ZkClientLockTest()).start();
			// 创建一个线程，倒计数器减1
			cdl.countDown();
		}

	}

	
	@Override
	public void run() {

		String result = "";
		long startTime = 0L;
		//等待其他线程初始化完成后, 一起往下执行
		try {
			cdl.await();

			//随机获取一家公司
			String component = components[new Random().nextInt(components.length)];

			startTime = System.currentTimeMillis();

			lock.lock();
			//获取12306票
			result = ticket12306.getTicket(component);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}finally {
			lock.unlock();

			long runTime = (System.currentTimeMillis() - startTime);
			System.out.println(result + ", 总耗时 = " + runTime + " 毫秒!");
		}
	}

	
}
